<template>
  <div class="userheader">
    <div class="search">
      <span class="name">流程节点</span>
      <el-input
        size="small"
        placeholder="流程节点名称"
        suffix-icon="el-icon-date"
        v-model="searchMessage.userPhone">
      </el-input>
    </div>
    <div class="search-button">
      <el-button type="primary" size="small" @click="searchBinding">查询</el-button>
      <!--由于第一个版本表单验证值得借鉴，所以先注释掉这部分代码-->
      <!--<el-button type="primary" size="small" @click="addBinding();dialogFormVisible = true">新增绑定</el-button>-->
      <router-link to="/flowBingdingAdd">
        <el-button type="primary" size="small" @click="handadd">新增绑定</el-button>
      </router-link>
    </div>
    <div>
      <el-dialog title="工单编辑绑定" :visible.sync="dialogFormVisible" style="width:80%;margin-left:10%;font-weight: bold">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm" size="small">
          <el-form-item label="工单模型列表" :label-width="formLabelWidth" prop="workOrder">
            <el-cascader
              :options="options3"
              change-on-select
              v-model="ruleForm.workOrder"
              placeholder="请选择"
              filterable
            ></el-cascader>
          </el-form-item>
          <el-form-item label="流程模型列表" :label-width="formLabelWidth" prop="flow">
            <el-cascader
              :options="options4"
              change-on-select
              v-model="ruleForm.flow"
              placeholder="请选择"
              filterable
            ></el-cascader>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm('ruleForm')" size="small">立即绑定</el-button>
          <el-button @click="dialogFormVisible = false" size="small">取 消</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
  import { mapState } from 'vuex';
  import axios from 'axios';
  import QS from 'qs';

    export default {
      name: "flowBingdingHeader",
      computed: {
        ...mapState([
          'flowList',
          'modelList',
          'bindingList'
        ]),
      },
      data(){
        return{
          dialogFormVisible: false,
          options3: [{
            value: 'zhinan',
            label: '指南',
            children: [{
              value: 'shejiyuanze',
              label: '设计原则',
            }, {
              value: 'daohang',
              label: '导航',
            }]
          },  {
            value: 'ziyuan',
            label: '资源',
            children: [{
              value: 'axure',
              label: 'Axure Components'
            }, {
              value: 'sketch',
              label: 'Sketch Templates'
            }, {
              value: 'jiaohu',
              label: '组件交互文档'
            }]
          }],
          options4: [],
          formLabelWidth: '110px',
          searchMessage: {
            userName: '',
            userPhone: '',
            userEmail: '',
          },
          ruleForm: {
            userid:'',
            workOrder: '',
            flow: '',
          },
          rules: {
            workOrder: [
              { required: true, message: '请选择工单模型', trigger: 'change' },
            ],
            flow: [
              { required: true, message: '请选择流程模型', trigger: 'change' },
              { pattern: /,{1}/, message: '请选择至最后一级选项' },
            ],
          }
        }
      },
      methods:{
        //新增绑定
        handadd(){
          const that = this;
          var model = {}
            model['clasz'] = "case" //调用模型接口，必须要为clasz赋值为case,这是后台固定的
            model['isTree'] = true
          function getUserAccount() {
            return axios.post('/api/cmdb/findModelByClasz',QS.stringify(model));
          }
          function getUserPermissions() {
            return axios.post('/api/workflow/findProcessDefinition');
          }
          axios.all([getUserAccount(), getUserPermissions()])
            .then(axios.spread(function (acct, perms) {
              // 两个请求现在都执行完成
              const flowDlata = perms.data.data.options;
              const flowCode = perms.data.code;
              const modelDlata = acct.data.data;
              const modelCode = acct.data.code;
              if (flowCode == "200"){
                that.$store.commit('flowListMethod',flowDlata);
                console.log(that.flowList);
                // that.options4 = flowDlata;
              }else if (flowCode == "201") {
                alert(flowCode + '您所查询的信息不存在！请重新输入!');
              }else{
                alert('错误代码:' + flowCode + '请联系系统管理员！');
              };
              if (modelCode == "200"){
                that.$store.commit('modelListMethodClear')   //赋值前先清空所有数据
                for (var i=0;i<modelDlata.length;i++){
                  var model = modelDlata[i];
                  console.log("model"+model)
                  // var option = {};
                  // option.label = model.name;
                  // option.value = model.id;
                  that.$store.commit('modelListMethod',model)
                }
                console.log('156' + that.modelList);
              }else if (modelCode == "201") {
                alert(modelCode + '您所查询的信息不存在！请重新输入!');
              }else{
                alert('错误代码:' + modelCode + '请联系系统管理员！');
              };

            }));
        },
        //新增绑定旧
        addBinding(){
          const that = this;
          function getUserAccount() {
            return axios.post('/api/cmdb/findModelByClasz');
          }
          function getUserPermissions() {
            return axios.post('/api/workflow/findProcessDefinition');
          }
          axios.all([getUserAccount(), getUserPermissions()])
            .then(axios.spread(function (acct, perms) {
              // 两个请求现在都执行完成
              const modelDlata = acct.data.data;
              const modelCode = acct.data.code;
              const flowDlata = perms.data.data.options;
              const flowCode = perms.data.code;
              if (modelCode == "200"){
                that.options3 = [];
                for (var i=0;i<modelDlata.length;i++){
                  var model = modelDlata[i];
                  var option = {};
                  option.label = model.name;
                  option.value = model.id;
                  that.options3.push(option);
                }
              }else if (modelCode == "201") {
                alert(modelCode + '您所查询的信息不存在！请重新输入!');
              }else{
                alert('错误代码:' + modelCode + '请联系系统管理员！');
              };
              if (flowCode == "200"){
                that.options4 = flowDlata;
              }else if (flowCode == "201") {
                alert(flowCode + '您所查询的信息不存在！请重新输入!');
              }else{
                alert('错误代码:' + flowCode + '请联系系统管理员！');
              };
            }))
            .catch(function (error) {
              console.log(error);
            });
        },
        //绑定关系查询
        searchBinding(){
          const that = this;
          axios.post('/api/case/selectCaseModelWorkflowNodeBinds')
            .then(function (bindingList) {
              var bindingListData = bindingList.data
              if (bindingListData.code == "200"){
                that.$store.commit('bindingListClear');
                for (var i=0; i<bindingListData.data.length; i++){
                  var bindingObject = {};
                    bindingObject.id = bindingListData.data[i].id;
                    bindingObject.workflowId = bindingListData.data[i].workflowId;
                    bindingObject.workflowName = bindingListData.data[i].workflowName;
                    bindingObject.workflowNodeId = bindingListData.data[i].workflowNodeId;
                    bindingObject.workflowNodeName = bindingListData.data[i].workflowNodeName;
                    bindingObject.workflowNodeVersion = bindingListData.data[i].workflowNodeVersion;
                    bindingObject.modelPid = bindingListData.data[i].modelPid;
                    bindingObject.modelPName = bindingListData.data[i].modelPName;
                    bindingObject.modelId = bindingListData.data[i].modelId;
                    bindingObject.modeName = bindingListData.data[i].modeName;
                  that.$store.commit('bindingListPush',bindingObject);
                  console.log(JSON.stringify(bindingObject));
                }
              } else {
                alert("no");
              };
            })
        },

        searchUser(){
          const that = this;
          const userMessage = {};
            userMessage['userName'] = this.searchMessage.userName;
            userMessage['userPhone'] = this.searchMessage.userPhone;
            userMessage['userEmail'] = this.searchMessage.userEmail;
          axios.post('/api/sys/sysUser/selectSysUser',QS.stringify(userMessage))
            .then(function (response) {
              const data = response.data;
              if (data.code == "200"){
                that.$store.commit('userTableList',data.data);  //通过commit操作store中mutations下的userTableList方法，完成对数组的赋值。
              }else if (data.code == "201") {
                alert(data.code + '您所查询的信息不存在！请重新输入!');
              }else{
                alert('错误代码:' + data.code + '请联系系统管理员！');
              };
            })
            .catch(function (error) {
              console.log(error);
            });
        },
        handleEdit(index, row) {
          this.$store.commit('userEditMethod',this.userTableData[index]);
          this.ruleForm.code = this.userEditData.userCode;
          this.ruleForm.name = this.userEditData.userName;
          this.ruleForm.password = this.userEditData.userPwd;
          this.ruleForm.emailNumber = this.userEditData.userEmail;
          this.ruleForm.phoneNumber = this.userEditData.userPhone;
          this.ruleForm.userid = this.userEditData.userId;
          // this.$router.push({ path: '/userEdit' });   //跳转到编辑页面的路由，由于页面改造暂行关闭
        },
        submitForm(formName) {
          this.$refs[formName].validate((valid) => {     //element-ui  表单验证
            const that = this;   //由于this指向已经不是 vue 的对象啦，所以必须重新对this进行定义。
            if (valid) {
              const userform = {};
              userform['userId'] = this.ruleForm.userid;
              userform['userCode'] = this.ruleForm.code;
              userform['userName'] = this.ruleForm.name;
              userform['userPwd'] = this.ruleForm.password;
              userform['userEmail'] = this.ruleForm.emailNumber;
              userform['userPhone'] = this.ruleForm.phoneNumber;
              userform['userGender'] = this.ruleForm.resource;
              axios.post('/api/sys/sysUser/updateSysUser',QS.stringify(userform)) //需要使用QS组件进行包裹，不然无法传值
                .then(function (response) {
                  const data = response.data
                  if (data.code == "200"){
                    alert('修改成功');
                    that.dialogFormVisible = false;
                    that.$emit('clickSearchUser', true);    //调用父组件中的clickSearchUser事件。
                    // that.$router.push({ path: '/user' });     //由于是弹窗，所以不用再进行页面跳转，暂且注释。
                  }else if (data.code == "500"){
                    alert(data.errorMessage);
                  }else{
                    alert('错误代码:' + data.code + '请联系系统管理员！')
                  }
                })
                .catch(function (error) {
                  console.log(error);
                });

            }else {
              console.log('提交失败，请验证数据是否符合规则！');
              // console.log('error submit!!');
              return false;
            }
          });
        },
      },
      mounted:function () {
        this.searchBinding();
      }
    }

</script>

<style scoped>
  .userheader{
    float: left;
    margin-bottom: 15px;
  }
  .search{
    float: left;
    display: flex;
  }
  .search-button{
    float: left;
    margin-left: 10px;
  }
  .name{
    float: right;
    display: flex;
    width: 90px;
    margin-left: 10px;
    line-height: 32px;
    text-align: right;
    color: #1f2d3d;
    font-size: 14px;
  }
  .spanName{
    /*float: left;*/
    /*line-height: 32px;*/
    /*display: inline-block;*/
  }

</style>
